//
//  MILLoginViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/12.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILLoginViewController.h"
#import "MILRegisterViewController.h"
#import "MILForgetPasswordViewController.h"
#import "LoginApi.h"
#import "TheThirdLoginApi.h"
#import "AppDelegate.h"
#import "modifyUserInformation.h"
#import "DTCSharePlatformManager.h"
#import <ShareSDK/ShareSDK.h>
#import "UIImageView+WebCache.h"
#import "GetUserInfoApi.h"

@interface MILLoginViewController ()
@property (weak, nonatomic) IBOutlet UIButton *myLoginBtn;
@property (weak, nonatomic) IBOutlet UITextField *myUserNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *myPasswordTextField;
@property (weak, nonatomic) IBOutlet UIButton *privacyButton;


@property(nonatomic,strong) MILRegisterViewController *registerVC;
@property(nonatomic,strong) MILForgetPasswordViewController *forgetVC;


@end

@implementation MILLoginViewController

#pragma mark -- UI
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //处理UI
    [self initMILLoginVCView];
    
    [self hideNavigationBottomLine];
    [self.navigationBar setHidden:YES];
    self.privacyButton.selected = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

//处理UI
- (void)initMILLoginVCView
{
    //处理文本输入框的提示文字颜色
    [self.myPasswordTextField setValue:[UIColor colorWithWhite:1 alpha:0.54] forKeyPath:@"_placeholderLabel.textColor"];
    [self.myUserNameTextField setValue:[UIColor colorWithWhite:1 alpha:0.54] forKeyPath:@"_placeholderLabel.textColor"];
    
    //登录按钮
    self.myLoginBtn.layer.cornerRadius = 20.0;
    self.myLoginBtn.clipsToBounds = YES;
}

#pragma mark -- 按钮点击事件
//忘记密码
- (IBAction)myForgetPasswordAction:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    self.forgetVC.updateBlock = ^(NSString *phone) {
        weakSelf.myUserNameTextField.text = phone;
    };
    [self.navigationController pushViewController:self.forgetVC animated:YES];
}
//登录
- (IBAction)myLoginAction:(UIButton *)sender {
    if (!self.myUserNameTextField.text || [self.myUserNameTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空！"];
        return;
    }
    if (!self.myPasswordTextField.text || [self.myPasswordTextField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"密码不能为空！"];
        return;
    }
    if (self.myPasswordTextField.text.length>16) {
        [SVProgressHUD showErrorWithStatus:@"密码长度不能超过20个"];
        return;
    }
    
    if (![self.myUserNameTextField.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码.."];
        return;
    }
    
    if (![self.myPasswordTextField.text isRegexPassword]) {
        [SVProgressHUD showErrorWithStatus:@"请输入6-16位字母或数字密码\n不包含除_@.之外的特殊符号"];
        return;
    }
    
    [[DTCloudManager defaultJNI_iOS_SDK]loginWithUsername:self.myUserNameTextField.text password:self.myPasswordTextField.text successCallback:^(NSDictionary *dic) {
        NSLog(@"dict = %@",dic[@"errmsg"]);
        if ([dic[@"errcode"] intValue] == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"您已安全登录！"];
            SAVE_OBJECT(dic[@"username"], USERNAME);
            SAVE_OBJECT(dic[@"password"], PASSWORD);
            SAVE_OBJECT(dic[@"data"][@"uid"], UID);
            SAVE_OBJECT(dic[@"data"][@"token"], TOKEN);
            SAVE_OBJECT(@"YES", LOGIN);   // 登录状态保存来设置根控制器
            
            [self GetUserInfo];
            [[AppDelegate defaultService] setRootViewController];
        } else {
            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        }

//        LoginApi *loginApi = [[LoginApi alloc]initWithDic:@{@"username":self.myUserNameTextField.text,@"password":self.myPasswordTextField.text}];
//        [loginApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//            //保存数据
//            [loginApi analyseResponseObject];
//            
//        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//            NSLog(@"%@",request.error);
//            [SVProgressHUD showErrorWithStatus:@"登陆失败！"];
//        }];
    } errorCallback:^(NSDictionary *dic) {
        
        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        
    }];
    


}

- (void)GetUserInfo {
    
    GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
    [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [userInfoApi analyseResponseObject];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"获取用户信息失败！"];
    }];
    
}

//注册
- (IBAction)myRegisterAction:(UIButton *)sender {
    
    __weak typeof(self) weakSelf = self;
    self.registerVC.updateBlock = ^(NSString *phone) {
        weakSelf.myUserNameTextField.text = phone;
    };
    [self.navigationController pushViewController:self.registerVC animated:YES];
}

//第三方登录
- (IBAction)theThirdLoginAction:(UIButton *)sender {
    switch (sender.tag)
    {
        case 100:
        {
            //微信
            [DTCSharePlatformManager wechartLoginSuccess:^(SSDKUser *user) {
                [self theThirdLoginWithOpenId:user.rawData[@"unionid"] andType:@"2" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
            } fail:^{
                
            }];
        }
            break;
        case 101:
        {
            //QQ
            [DTCSharePlatformManager qqLoginSuccess:^(SSDKUser *user) {
                [self theThirdLoginWithOpenId:user.uid andType:@"1" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
            } fail:^{
                
            }];
        }
            break;
        case 102:
        {
            //微博
            [DTCSharePlatformManager weiboLoginSuccess:^(SSDKUser *user) {
                [self theThirdLoginWithOpenId:user.uid andType:@"3" andModifyInformationWithSex:[NSString stringWithFormat:@"%lu",(unsigned long)user.gender+1] andNickname:user.nickname andIcon:user.icon];
            } fail:^{
                
            }];
        }
            break;
            
        default:
            break;
    }

}

- (IBAction)didClickPrivacyButton:(id)sender {
    UIButton *button = sender;
    self.privacyButton.selected = !self.privacyButton.selected;
    self.myPasswordTextField.secureTextEntry = button.selected;
}


#pragma mark -- 第三方登录
- (void)theThirdLoginWithOpenId:(NSString *)openid andType:(NSString *)loginType andModifyInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon
{
    [[DTCloudManager defaultJNI_iOS_SDK] loginWithThirdOpenId:openid successCallback:^(NSDictionary *dic) {
        TheThirdLoginApi *loginApi = [[TheThirdLoginApi alloc]initWithDic:@{@"openid":openid,@"type":loginType}];
        [loginApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            //保存数据
            NSDictionary * dict = [loginApi responseJSONObject];
            NSLog(@"dict = %@",dict[@"errmsg"]);
            if ([dict[@"errcode"] intValue] == 0) {
                SAVE_OBJECT(dict[@"data"][@"uid"], UID);
                SAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
                //            NSLog(@"login = %@",EXRACT_OBJECT(LOGINING));
                //修改用户信息
                [self modifyUserInformationWithSex:sex andNickname:nickname andIcon:icon andFirst:[dict[@"data"][@"is_first_login"]boolValue]];
                
            } else {
                [SVProgressHUD showErrorWithStatus:dict[@"errmsg"]];
            }
            
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSLog(@"%@",request.error);
            [SVProgressHUD showErrorWithStatus:@"登陆失败！"];
        }];
    } errorCallback:^(NSDictionary *dic) {
        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
    }];

    
}

//修改用户信息
- (void)modifyUserInformationWithSex:(NSString *)sex andNickname:(NSString *)nickname andIcon:(NSString *)icon andFirst:(BOOL)first
{
//    if (first) {
        UIImageView *imageView = [[UIImageView alloc]init];
        [[AppDelegate defaultService].window addSubview:imageView];
        imageView.hidden = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:icon] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
            [UIImageJPEGRepresentation(image, 1.0f) writeToFile:PorPath atomically:YES];
            
            modifyUserInformation *modifyApi = [[modifyUserInformation alloc]initWithDic:@{@"nickname":nickname,@"sex":sex,@"image":PorPath}];
            [modifyApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                
                NSDictionary *dic = [modifyApi responseJSONObject];
                NSLog(@"errcode dic = %@",dic[@"errmsg"]);
                if([dic[@"errcode"] intValue] == 0) {
                    [SVProgressHUD showSuccessWithStatus:@"用户登陆成功"];
                    SAVE_OBJECT(@"YES", LOGIN);   // 登录状态保存来设置根控制器
                    SAVE_OBJECT(sex, SEX);
                    SAVE_OBJECT(nickname, NICKNAME);
                    SAVE_OBJECT(icon, ICON);
                    [SVProgressHUD dismiss];
                    //跳转主页
                    [[AppDelegate defaultService] setRootViewController];
                } else {
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                }
                
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
                [SVProgressHUD showErrorWithStatus:@"请求失败"];
            }];
        }];
//    }else{
//        SAVE_OBJECT(@"YES", LOGIN);   // 登录状态保存来设置根控制器
//        [[AppDelegate defaultService]setRootViewController];
//    }
}


#pragma mark -- 懒加载
- (MILRegisterViewController *)registerVC
{
    if(!_registerVC)
    {
        _registerVC = [[MILRegisterViewController alloc]init];
    }
    return _registerVC;
}
- (MILForgetPasswordViewController *)forgetVC
{
    if(!_forgetVC)
    {
        _forgetVC = [[MILForgetPasswordViewController alloc]init];
    }
    return _forgetVC;
}


@end
